package com.lyf.security.login.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @AUTHOR LYF
 * @DATE 2022/1/21
 * @VERSION 1.0
 * @DESC 登录拦截器,进行访问前和后的处理,true放行,false拦截
 *
 * 拦截除Login 资源以外的请求
 */
@Configuration
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        System.out.println("登陆拦截...");
        if(token==null){
            PrintWriter printWriter = response.getWriter();
            printWriter.write("No Token（error:1001）");
            return false;//为空需要进行重新登录
        }else {
            // 解析并检验token,
            String tokenCache =(String) redisTemplate.opsForValue().get("token:"+token);
            if(tokenCache==null){
                PrintWriter printWriter = response.getWriter();
                printWriter.write("Token has Expired（error:1002）");
                return false;
                //throw new Exception("无效token");
            }
            // 查询到该token,则放行
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }



}
